package top.forlenet.filter;


import top.forlenet.common.CommonConstants;
import top.forlenet.common.CommonResult;
import top.forlenet.entity.User;
import top.forlenet.utils.JsonUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@WebFilter(filterName = "LoginFilter", value = "/*",
        // filter的初始化参数，指定哪些资源直接放行
        initParams = {@WebInitParam(name = "pass", value = "/login,.html,.css,.js")})
public class LoginFilter implements Filter {

    // 存储需要放行的资源
    private List<String> passList;
    @Override
    public void init(FilterConfig config) throws ServletException {
        passList = new ArrayList<>();
        String value = config.getInitParameter("pass");
        if (value != null && value.length() > 0) {
            String[] split = value.split(",");
            passList = Arrays.asList(split);
        }
    }
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        // 获取访问的资源的路径
        String requestURI = req.getRequestURI();
        System.out.println(requestURI);

        // 判断访问的资源是否是需要放行的资源
        if (checkUrl(requestURI)) {
            chain.doFilter(request, response);
        } else {
            HttpSession session = req.getSession();
            User loginUser = (User) session.getAttribute(CommonConstants.LOGIN_USER);
            if (loginUser == null) {
                // 返回json格式数据
                res.getWriter().write(JsonUtils.bean2json(CommonResult.error(CommonConstants.FORBIDDEN, "没有登录，无法访问")));
                return;
            } else {
                chain.doFilter(request, response);
            }
        }
    }

    private boolean checkUrl(String url) {
        for (String pass : passList) {
            if (url.endsWith(pass)) {
                return true;
            }
        }
        return false;
    }
}
